﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XPressify.Data;
using XPressify.Data.Helpers;
using XPressify.Helpers;
using XPressify.Models;

namespace XPressify.Controllers
{
    public class MessageController : BaseController
    {
        [Authorize]
        public ActionResult CreateMessage(Guid id)
        {
            var user = CurrentUser;
            var currentUserProfilePicturePath = Repository.GetProfilePicturePath(user.Id);
            var thread = Repository.AsQueryable<Thread>().SingleOrDefault(th => th.Id == id);
            var listMessages = new List<Message>(thread.Messages).OrderBy(mes => mes.Created);
            var listCreatorProfilePath = new List<string>();
            foreach (var message in listMessages)
            {
                var creator = message.BaseSubject;
                var creatorProfilePicturePath = Repository.GetProfilePicturePath(creator.Id);
                listCreatorProfilePath.Add(creatorProfilePicturePath);
            }
            
            var model = new MessageCreateModel()
                            {
                                Message = "",
                                PreviousMessages = listMessages.ToArray(),
                                CurrentUserName = user.FullName,
                                ThreadId = thread.Id,
                                CurrentUser = user,
                                CreatorProfilePicturePath = listCreatorProfilePath.ToArray(),
                                CurrentUserProfilePicturePath = currentUserProfilePicturePath,
                                ThreadSubject = thread.Subject,
                                IsAjaxRequest = Request.IsAjaxRequest()
                            };
            return View(model);
        } 

        //
        // POST: /Message/Create
        [Authorize]
        [HttpPost]
        public ActionResult CreateMessage(MessageCreateModel model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    var user = CurrentUser;
                    var thread = Repository.AsQueryable<Thread>().SingleOrDefault(th => th.Id == model.ThreadId);
                    var message = new Message
                    {
                        Id = Guid.NewGuid(),
                        BaseSubject = user,
                        Created = DateTime.Now,
                        Type = BaseMessageType.Message,
                        Thread = thread,
                        Body = model.Message
                    };
                    Repository.AddObject(message);
                    Repository.SaveChanges();

                    foreach (var participant in thread.ThreadParticipants.Select(x => x.BaseSubject).OfType<User>())
                    {
                        if(user.Id == participant.Id)
                            continue;
                        var threadParticipant = Repository.AsQueryable<ThreadParticipant>().SingleOrDefault(x => x.Thread.Id == thread.Id && x.BaseSubject.Id == participant.Id);
                        threadParticipant.IsDeleted = false;
                        threadParticipant.IsRead = false;
                        threadParticipant.NewMessage = true;        //they got new messege
                        var mailModel = new MessageSendEmailModel
                        {
                            Created = thread.Created,
                            Sender = thread.BaseSubject.FullName,
                            MessageBody = message.Body,
                            Subject = thread.Subject,
                            ThreadId = thread.Id,
                            Receiver = participant
                        };
                        SendEmail(mailModel);
                    }
                    Repository.SaveChanges();
                    return RedirectToAction("ThreadList", "Thread",new {id = thread.Id});
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model);
        }

#region Email sending

        [Authorize]
        public bool SendEmail(MessageSendEmailModel model)
        {
            var user = CurrentUser;
            var viewData = new
            {
                XSettings.SiteName,
                YourName = user.FullName,
                model.Sender,
                model.Created,
                model.MessageBody, 
                model.Subject,
                ReplyUrl =
                    new Uri(HttpContext.Request.Url, Url.Action("CreateMessage", "Message", new { id = model.ThreadId })).
                        ToString(),
                YourProfileUrl =
                       new Uri(HttpContext.Request.Url,
                               Url.Action("ProfileView", "Profile", new { id = user.Id })).ToString(),
                XSettings.SiteUrl
            };

            var viewDictionary = viewData.ToViewDataDictionary();

            // send an activation email
            return SendTemplatedEmail(new List<string> { model.Receiver.Email },
                                                   String.Format("{0} site: New message", XSettings.SiteName),
                                                   "~/Views/Email/MessageEmailSend.cshtml", viewDictionary);
        }

#endregion
        
    }
}
